package com.wayz.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.wayz.entity.pojo.play.DPlayHeartbeat;
import com.wayz.mapper.DPlayHeartbeatDAO;
import com.wayz.rabbitmq.MqDefinition;
import com.wayz.util.ShardStrategyHelper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class PlayHeartbeatListener {
	private final String TABLE_NAME="t_play_heartbeat";


	/** 处理批次大小 */
	private static final Integer LISTSIZE = 200;
	/** 缓冲提交时间(秒) */
	private static final Integer DELAY_SEC = 60;
	/** 分批集合 */
	private static List<DPlayHeartbeat> heartList = new ArrayList<>(LISTSIZE);
	/** 播放器心跳DAO */
	@Resource(name = "dPlayHeartbeatDAO")
	private DPlayHeartbeatDAO dPlayHeartbeatDAO = null;
	Long tick = System.currentTimeMillis();

	@RabbitListener(queues= MqDefinition.PLAY_HEART_BEAT_QUEUE)
	@DS(value = "play")
	public void onMessage(String msg) {
		try {
			DPlayHeartbeat dPlayHeartbeatCreate = JSONObject.toJavaObject(JSONObject.parseObject(msg),
					DPlayHeartbeat.class);
			heartList.add(dPlayHeartbeatCreate);
			if (heartList.size() >= LISTSIZE || System.currentTimeMillis() - tick >= DELAY_SEC) {
				tick = System.currentTimeMillis();
				dPlayHeartbeatDAO.batchCreate(heartList, ShardStrategyHelper.getTodayDateTableName(TABLE_NAME));
				heartList.clear();
			}
		}
		catch (Exception e) {
			heartList.clear();
			e.printStackTrace();
		}

	}
}
